package com.example.art_cloud_backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.art_cloud_backend.exception.BusinessException;
import com.example.art_cloud_backend.exception.ErrorCode;
import com.example.art_cloud_backend.exception.ThrowUtils;
import com.example.art_cloud_backend.manager.CosManager;
import com.example.art_cloud_backend.manager.upload.FilePictureUpload;
import com.example.art_cloud_backend.manager.upload.PictureUploadTemplate;
import com.example.art_cloud_backend.manager.upload.UrlPictureUpload;
import com.example.art_cloud_backend.model.dto.file.UploadPictureResult;
import com.example.art_cloud_backend.model.dto.picture.PictureQueryRequest;
import com.example.art_cloud_backend.model.dto.picture.PictureReviewRequest;
import com.example.art_cloud_backend.model.dto.picture.PictureUploadByBatchRequest;
import com.example.art_cloud_backend.model.dto.picture.PictureUploadRequest;
import com.example.art_cloud_backend.model.entity.Picture;
import com.example.art_cloud_backend.model.entity.User;
import com.example.art_cloud_backend.model.enums.PictureReviewStatusEnum;
import com.example.art_cloud_backend.model.vo.picture.PictureVO;
import com.example.art_cloud_backend.model.vo.user.UserVO;
import com.example.art_cloud_backend.service.PictureService;
import com.example.art_cloud_backend.mapper.PictureMapper;
import com.example.art_cloud_backend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-08-03 20:37:00
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param inputSource 输入源
     * @param pictureUploadRequest 图片上传请求
     * @param loginUser 登录用户
     * @return 图片上传结果
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(inputSource == null, ErrorCode.NO_AUTH);
        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            // 获取图片信息
            Picture oldPicture = this.getById(pictureId);
            // 图片获取失败，报错
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 只有管理员 || 上传图片的用户可以修改
            if (userService.isAdmin(loginUser) || oldPicture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
        }
        // 上传图片，得到信息
        // 按照用户 id 划分目录
        String uploadPathPrefix = String.format("public/%s", loginUser.getId());
        // 判断上传源
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPictureTemplate(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        // 设置缩略图
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = uploadPictureResult.getPicName();
        // 图片名称
        if (pictureUploadRequest != null && CharSequenceUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        // 填充审核参数
        this.fillReviewParams(picture, loginUser);
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        boolean result = this.saveOrUpdate(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
        return PictureVO.objToVo(picture);
    }

    /**
     * 获取查询条件
     * @param pictureQueryRequest 图片查询请求
     * @return 查询条件
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 转换图片VO
     * @param picture 图片
     * @param request 请求
     * @return 图片VO
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     * @param picturePage 图片分页
     * @param request 请求
     * @return 图片VO分页
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 批量抓取和创建图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return 成功创建的图片数
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 查询关键词
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        // 最大爬取数量
        final int MAX_COUNT = 30;
        // 校验参数
        ThrowUtils.throwIf(CharSequenceUtil.isBlank(searchText), ErrorCode.PARAMS_ERROR, "关键词不能为空");
        ThrowUtils.throwIf(count == null || count <= 0, ErrorCode.PARAMS_ERROR, "数量不能小于等于0");
        ThrowUtils.throwIf(count > MAX_COUNT, ErrorCode.PARAMS_ERROR, "数量不能大于" + MAX_COUNT + "条");
        // 抓取地址
        String fetchUrl = String.format("https://www.bing.com/images/search?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取页面失败");
        }
        // 获取页面元素
        Element div = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(ObjUtil.isNull(div), ErrorCode.PARAMS_ERROR, "获取元素失败");
        // 获取图片列表元素
        Elements imgElementList = div.select("img.mimg");
//        Elements imgElementList = div.select(".iusc");  // 修改选择器，获取包含完整数据的元素
        // 记录上传成功的数量
        int uploadCount = 0;
        // 名称前缀
        String prefix = pictureUploadByBatchRequest.getNamePrefix();
        // 如果没有前缀，使用关键词
        if (StrUtil.isBlank(prefix)) {
            prefix = searchText;
        }
        // 遍历元素列表
        for (Element imgElement : imgElementList) {
            // 获取图片URL
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("图片URL为空，已跳过：{}", fileUrl);
                continue;
            }
            // 处理图片上传地址
            int questionMarkIndex = fileUrl.indexOf("?");
            // 浏览器的图片URL会加入其他参数去限制图片的显示，例如
            // https://th.bing.com/th/id/OIP.BS9tAD8f7fM6tt0LPC2RlwHaEd?w=302&h=181&c=7&r=0&o=7&pid=1.7&rm=3
            // ?w=302&h=181：限制宽高，c=7：限制图片质量，rm=3：限制图片格式
            // 所以为了得到更高的图片质量，以及最纯净的图片URL，需要取出 ? 之后的参数
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            // 设置图片名称
            if (StrUtil.isNotBlank(prefix)) {
                // 拼接名称
                String name = prefix + "_" + (uploadCount + 1);
                pictureUploadRequest.setPicName(name);
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id={}", pictureVO.getId());
                // 增加上传成功数量
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败，url={}", fileUrl, e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 校验图片
     * @param picture 图片
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 审核图片
     *
     * @param pictureReviewRequest 请求参数
     * @param loginUser 审核人
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1、校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取老图
        Picture oldPicture = this.getById(pictureReviewRequest.getId());
        // 图片不存在，报错
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR, "ID不存在");
        // 2、状态判断
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        // 根据传入的审核状态获取枚举值
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        // 如果查询出的 枚举值为空，说明传入的枚举值不符合系统设定
        ThrowUtils.throwIf(reviewStatusEnum == null, ErrorCode.PARAMS_ERROR, "审核状态错误");
        // 不能审核相同状态
        ThrowUtils.throwIf(reviewStatus.equals(oldPicture.getReviewStatus()), ErrorCode.PARAMS_ERROR, "已是该审核状态");
        // 3、更新数据库
        // 新建Picture去执行更新操作：因为新对象去执行操作，我们只需要修改需要的参数，而不是更新整个对象，一定程度上可以优化性能
        Picture savePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, savePicture);
        // 填入审核人
        savePicture.setReviewerId(loginUser.getId());
        // 审核时间
        savePicture.setReviewTime(new Date());
        // 更新数据
        boolean result = this.updateById(savePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "修改审核状态失败");
    }

    /**
     * 填充审核信息
     * @param picture 图片信息
     * @param user 用户信息
     */
    @Override
    public void fillReviewParams(Picture picture, User user) {
        // 如果是管理员，自动过审
        if (userService.isAdmin(user)) {
            picture.setReviewerId(user.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public void clearPictureFile(Picture picture) {
        // 1. 校验参数
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        String pictureUrl = picture.getUrl();
        // 判断图片是否被多条记录使用
        Long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        if (count > 1) {
            return;
        }
        // 2. 删除图片
        cosManager.deleteObject(pictureUrl);
        // 清理缩略图
        String thumbnailUrl = picture.getThumbnailUrl();
        if (thumbnailUrl != null) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }
}




